<script setup lang="ts">
import { bindMobileAPI, loginByQQAPI } from '@/apis/user'
import { RulesCodes, RulesMobile } from '@/utils/rules'
import { onMounted, ref } from 'vue'

const openId = ref('')
const isNeedBind = ref(false)
const mobile = ref('')
const code = ref('')

// 导入组合式函数
import { useMobileCode } from '@/composables/useMobileCode'
import type { UserType } from '@/types/user'
import { showSuccessToast } from 'vant'
const { onSend, time, formRef } = useMobileCode(mobile, 'bindMobile')
import { useUserStore } from '@/stores'
import router from '@/router'
const store = useUserStore()
onMounted(() => {
    if (QC.Login.check()) {
        // 获取 openId 用户身份的唯一标识
        QC.Login.getMe((id) => {
            openId.value = id
            // 调用接口函数
            loginByQQAPI(id)
                .then((res) => {
                    // 登录成功 提示用户 跳转页面 将数据存储到本地存储里面
                    loginSuccess(res.data)
                })
                .catch(() => {
                    // 登录失败 需要显示绑定手机号码的页面
                    isNeedBind.value = true
                })
        })
    }
})

const loginSuccess = (data: UserType) => {
    store.setUser(data)
    router.replace('/user')
    showSuccessToast('登录成功')
}

const onSubmit = async () => {
    // 发送请求 绑定手机号码
    const res = await bindMobileAPI({
        mobile: mobile.value,
        code: code.value,
        openId: openId.value
    })
    // 绑定成功 提示用户 跳转页面 将数据存储到本地存储里面
    loginSuccess(res.data)
}
</script>

<template>
    <div class="login-page" v-if="isNeedBind">
        <cp-nav-bar></cp-nav-bar>
        <div class="login-head">
            <h3>手机绑定</h3>
        </div>
        <van-form autocomplete="off" ref="formRef" @submit="onSubmit">
            <van-field name="mobile" placeholder="请输入手机号" v-model="mobile" :rules="RulesMobile"></van-field>
            <van-field name="code" placeholder="请输入验证码" v-model="code" :rules="RulesCodes">
                <template #button>
                    <span class="btn-send" @click="onSend" :class="{ active: time > 0 }">
                        {{ time > 0 ? `${time}秒后发送验证码` : '发送验证码' }}
                    </span>
                </template>
            </van-field>
            <div class="cp-cell">
                <van-button block round type="primary" native-type="submit">
                    立即绑定
                </van-button>
            </div>
        </van-form>
    </div>
</template>

<style lang="scss" scoped>
@import '@/styles/login.scss';
</style>
